﻿<%@ WebHandler Language="C#" Class="Create" %>

using System;
using System.Web;
using System.Text;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using Company.StudyClub.Model;
using Company.StudyClub.BLL.Course;
using Company.StudyClub.BLL.Common;
using Company.StudyClub.BLL.Tag;

public class Create : IHttpHandler {
    
    private HttpHelper helper = new HttpHelper();
    
    public void ProcessRequest (HttpContext context) {
        HttpResponse response = context.Response;

        switch (helper.GetString("type"))
        {           
            case "checkserialnumber":
                CheckSerialNumber(response);
                break;
            case "createcourse":
                CreateCourse(response);
                break;  
            case "updatecourse":
                UpdateCourse(response);
                break;        
            case "uploadscorm":
                UploadScorm(context);
                break;
            case "importsection":
                DoImportSection(context);
                break;
            case "uploadcovericon":
                UploadCoverIcon(context);
                break;
            case "deletecovericon":
                DeleteCoverIcon(context);
                break;
            case "deletecourse":
                DeleteCourse(context);
                break;
            default: break;
        }
    }

    private void CheckSerialNumber(HttpResponse response)
    {
        CourseBLL objBLL = new CourseBLL();

        bool result = objBLL.CheckSerialNumber(helper.GetString("serialnumber"));

        if (result)
        {
            response.Write("false");
        }
        else
        {
            response.Write("true");
        }
    }

    private void CreateCourse(HttpResponse response)
    {
        Course_Info model = new Course_Info();
        model.CourseName = helper.GetString("cname");
        model.CourseType = helper.GetInt("ctype");
        model.PlayLength = helper.GetInt("playlength") * 60;
        model.IsPublic = helper.GetInt("ispublic");
        model.IsRecommend = helper.GetInt("isrecommend");
        model.Keywords = helper.GetString("keywords");
        model.LecturerIntro = helper.GetString("intro");
        model.Description = helper.GetString("description");
        model.SerialNumber = helper.GetString("serialnumber").ToUpper();
        model.Status = 0;
        model.CatalogID = helper.GetInt("catalogid");
        model.CoverIcon = helper.GetString("covericon");
        model.SchoolID = helper.CurrentUser.SchoolID;
        model.CreatorID = helper.CurrentUser.UserID;

        CourseBLL objBLL = new CourseBLL();
        int courseId = objBLL.Add(model);

        string[] tagids = helper.GetString("tagids").Split(',');

        TagCoursesBLL objTagCourseBLL = new TagCoursesBLL();
        
        for (int i = 0; i < tagids.Length; i++)
        {
            if (!string.IsNullOrEmpty(tagids[i]))
            {
                int tagId = int.Parse(tagids[i]);

                Tag_Courses tcModel = new Tag_Courses();
                tcModel.CourseID = courseId;
                tcModel.TagID = tagId;

                objTagCourseBLL.Add(tcModel);
            }
        }
        
        CatalogBLL objCatalog = new CatalogBLL();
        objCatalog.UpdateTotalCourses(model.CatalogID, 1);
        
        response.Write(courseId.ToString());
    }

    private void UpdateCourse(HttpResponse response)
    {
        CourseBLL objBLL = new CourseBLL();

        Course_Info model = objBLL.GetEmptyModel();
        
        model.CourseID = helper.GetInt("courseid");
        model.CourseName = helper.GetString("cname");
        model.PlayLength = helper.GetInt("playlength") * 60;
        model.IsPublic = helper.GetInt("ispublic");
        model.IsRecommend = helper.GetInt("isrecommend");
        model.Keywords = helper.GetString("keywords");
        model.LecturerIntro = helper.GetString("intro");
        model.Description = helper.GetString("description");        
        model.CatalogID = helper.GetInt("catalogid");
        model.CoverIcon = helper.GetString("covericon");        
       
        objBLL.Update(model);

        int curcatalogid = helper.GetInt("curcatalogid");

        if (curcatalogid != model.CatalogID)
        {
            CatalogBLL objCatalog = new CatalogBLL();
            objCatalog.UpdateTotalCourses(model.CatalogID, 1);
            objCatalog.UpdateTotalCourses(curcatalogid, -1);
        }

        string[] tagids = helper.GetString("tagids").Split(',');

        TagCoursesBLL objTagCourseBLL = new TagCoursesBLL();

        objTagCourseBLL.Delete(0, model.CourseID);
        
        for (int i = 0; i < tagids.Length; i++)
        {
            if (!string.IsNullOrEmpty(tagids[i]))
            {
                int tagId = int.Parse(tagids[i]);

                Tag_Courses tcModel = new Tag_Courses();
                tcModel.CourseID = model.CourseID;
                tcModel.TagID = tagId;

                objTagCourseBLL.Add(tcModel);
            }
        }

        response.Write("1");
    }

    private void UploadScorm(HttpContext context)
    {
        try
        {
            HttpPostedFile oFile = context.Request.Files["Filedata"];

            int courseId = helper.GetInt("cid");

            string m_path = HttpContext.Current.Server.MapPath(@context.Request["folder"]);

            DeleteOldFile(m_path);

            Directory.CreateDirectory(m_path);

            SectionBLL objSection = new SectionBLL();
            objSection.DeleteByCourseID(courseId);

            string m_filepath = Path.Combine(m_path, oFile.FileName);
            oFile.SaveAs(m_filepath);
        }
        catch (Exception ex)
        {
            Utility.SaveErrorLogFile(ex.Message);
        }

        context.Response.Write("1");
    }

    private void DoImportSection(HttpContext context)
    {
        try
        {
            string filename = context.Server.MapPath(helper.GetString("filePath"));
            string directory = Path.GetDirectoryName(filename) + "\\";
            int courseId = helper.GetInt("cid");

            UnZipFile(filename, directory);

            ImportSections(courseId, directory);
        }
        catch (Exception ex)
        {
            Utility.SaveErrorLogFile(ex.Message);
        }

        context.Response.Write("1");
    }

    private void DeleteOldFile(string folderPath)
    {
        if (Directory.Exists(folderPath))
            Directory.Delete(folderPath, true);
    }

    private void DeleteOldSections(int CourseID)
    {
        SectionBLL objBLL = new SectionBLL();
        objBLL.Delete(CourseID);
    }

    protected void UnZipFile(string filepath, string unZipFolder)
    {
        try
        {
            SuperZip.Instance().UnZipFile(filepath, unZipFolder);

            Thread.Sleep(1000);

            FileInfo objFile = new FileInfo(filepath);
            if (objFile.Exists)
            {
                objFile.Delete();
            }
        }
        catch(Exception ex)
        {
            Utility.SaveErrorLogFile(ex.Message);
        }
    }

    protected void ImportSections(int CourseID,string folderPath)
    {
        string ls_ErrText = "";
        string xmlFilePath = Path.Combine(folderPath ,"imsmanifest.xml");
        if (File.Exists(xmlFilePath))
        {
            XmlHelper xmlHelper = new XmlHelper(xmlFilePath);
            xmlHelper.InitSectionList(CourseID, ref ls_ErrText);
            List<Course_Section> lstSection = xmlHelper.SectionList;
            if (ls_ErrText.Trim() == "")
            {
                SectionBLL objBLL = new SectionBLL();

                foreach (Course_Section model in lstSection)
                {
                    objBLL.Add(model);
                }
            }
            else
            {
                if (!Directory.Exists(folderPath))
                    Directory.Delete(folderPath, true);
            }
        }
        else
        {
            if (!Directory.Exists(folderPath))
                Directory.Delete(folderPath, true);
        }
    }

    private void UploadCoverIcon(HttpContext context)
    {
        try
        {
            HttpPostedFile oFile = context.Request.Files["Filedata"];

            string directory = HttpContext.Current.Server.MapPath(@context.Request["folder"]);
            string filename = helper.GetString("covericon");

            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);

            string m_filepath = Path.Combine(directory, filename.Replace("_S", "_O"));
            oFile.SaveAs(m_filepath);

            CutImage objImage = new CutImage();
            objImage.CutImageBySize(m_filepath, m_filepath.Replace("_O", "_S"), 160, 120);

            int courseId = helper.GetInt("courseid");
            if (courseId > 0)
            {
                CourseBLL objBLL = new CourseBLL();
                objBLL.UpdateCoverInfo(courseId, filename);
            }
        }
        catch(Exception ex)
        {
           Utility.SaveErrorLogFile(ex.Message);
        }
        
        context.Response.Write("1");
    }   

    private void DeleteCoverIcon(HttpContext context)
    {
        string filepath = context.Server.MapPath("~/data/coursepicture/" + helper.GetString("filename"));

        if (File.Exists(filepath))
        {
            File.Delete(filepath);
        }
        
        string oPicture = filepath.Replace("_S", "_O");
        if (File.Exists(oPicture))
        {
            File.Delete(oPicture);
        }

        int courseId = helper.GetInt("courseid");
        if (courseId > 0)
        {
            CourseBLL objBLL = new CourseBLL();
            objBLL.UpdateCoverInfo(courseId, "");
        }
        
        context.Response.Write("1");
    }

    private void DeleteCourse(HttpContext context)
    {
        try
        {
            string[] cids = helper.GetString("cids").Split(',');

            for (int i = 0; i < cids.Length; i++)
            {
                if (cids[i] == string.Empty)
                    continue;

                int courseId = int.Parse(cids[i]);
                
                DeleteCourseByID(context, courseId);
            }           
            
            context.Response.Write("1");
        }
        catch (Exception ex)
        {
            Utility.SaveErrorLogFile(ex.Message);
            
            context.Response.Write("0");
        }       
    }

    private void DeleteCourseByID(HttpContext context,int courseId)
    {
        CourseBLL objBLL = new CourseBLL();       

        Course_Info model = objBLL.GetModel(courseId);

        string coursefolder = context.Server.MapPath("~/data/course/" + model.SchoolID + "/" + model.SerialNumber + "/");

        if (Directory.Exists(coursefolder))
        {
            Directory.Delete(coursefolder, true);
        }

        string coverIcon = context.Server.MapPath("~/data/coursepicture/" + model.CoverIcon);

        if (File.Exists(coverIcon))
        {
            File.Delete(coverIcon);
        }

        string ocoverIcon = coverIcon.Replace("_S", "_O");

        if (File.Exists(ocoverIcon))
        {
            File.Delete(ocoverIcon);
        }

        objBLL.Delete(courseId);
    }
    
    public bool IsReusable
    {
        get {
            return false;
        }
    }

}